import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

import 'package:series_play/bean/local_video_data.dart';
import 'package:series_play/comm/comm_constant.dart';
import 'package:series_play/generated/assets.dart';
import 'package:path/path.dart' as p;
import '../../widget/video/controller/base_feed_video_controller.dart';

class ForYouController extends BaseFeedVideoController {
  @override
  void onReady() {
    super.onReady();
    onRefresh();
  }

  @override
  Future<List<LocalVideoData>> onLoad(int page,
      int pageSize,
      bool isRefresh,) async {
    final video1 = await copyAssetVideo(Assets.video1);
    final video2 = await copyAssetVideo(Assets.video2);
    final video3 = await copyAssetVideo(Assets.video3);
    final video4 = await copyAssetVideo(Assets.video4);
    final video5 = await copyAssetVideo(Assets.video5);

    final list = [
      LocalVideoData(
        cover: CommConstant.fuckImgData[3],
        video: Assets.video1,
        localUrl: video1,
      ),
      LocalVideoData(
        cover: CommConstant.fuckImgData[4],
        video: Assets.video2,
        localUrl: video2,
      ),
      LocalVideoData(
        cover: CommConstant.fuckImgData[5],
        video: Assets.video3,
        localUrl: video3,
      ),
      LocalVideoData(
        cover: CommConstant.fuckImgData[6],
        video: Assets.video4,
        localUrl: video4,
      ),
      LocalVideoData(
        cover: CommConstant.fuckImgData[7],
        video: Assets.video5,
        localUrl: video5,
      ),
    ];

    if (isRefresh) {
      // 初始化
      List<Future> futureList = [
        createPlayer2(0, list[0].localUrl!),
        createPlayer2(1, list[1].localUrl!)
      ];
      await Future.wait(futureList);
      onTogglePlay(0);
    }

    return list;
  }

  /// 复制指定的 assets/video/xx.mp4 到本地可见目录，并返回本地文件路径
  Future<String> copyAssetVideo(String assetPath) async {
    // 1. 读取 asset 字节
    final ByteData data = await rootBundle.load(assetPath);
    final List<int> bytes = data.buffer.asUint8List();

    // 2. 获取应用目录
    final Directory appDir = await getApplicationSupportDirectory();

    // 3. 创建 video 目录
    final Directory videosDir = Directory('${appDir.path}/videos');
    if (!videosDir.existsSync()) {
      await videosDir.create(recursive: true);
    }

    // 4. 文件名
    final String fileName = p.basename(assetPath);

    // 5. 构造目标文件
    final File outFile = File('${videosDir.path}/$fileName');

    // 如果文件已存在并且大小一致，直接返回
    if (await outFile.exists()) {
      final int localSize = await outFile.length();
      if (localSize == bytes.length) {
        return outFile.path;
      } else {
        await outFile.delete(); // 删除损坏文件
      }
    }

    // 6. 安全写入（避免多个写操作覆盖导致花屏）
    await outFile.writeAsBytes(bytes, flush: true);

    // 7. 打开文件强制底层刷新（移动端替代 fsync 最稳定的方法）
    final raf = await outFile.open(mode: FileMode.read);
    await raf.close();

    // 8. 校验写入长度
    final int wrote = await outFile.length();
    if (wrote != bytes.length) {
      throw Exception("视频写入不完整：$assetPath");
    }

    return outFile.path;
  }

// @override
// Future<void> onPageChanged(int i) {
//   // 倒数第五个时 提前加载下一页
//   if (i == dataList.length - 5 && !isLoading.value) {
//     onLoadMore();
//   }
//
//   // 如果已经是最后一个了 并且没有加载更多 去加载下一页
//   if (i == dataList.length - 1 && !isLoading.value) {
//     // 网络差时 倒数第五个时可能失败
//     onLoadMore();
//   }
//   return super.onPageChanged(i);
// }
}
